/*
 * Copyright (c) 2018, apexes.net. All rights reserved.
 *
 *         http://www.apexes.net
 *
 */
package net.apexes.commons.eventbus;

import java.lang.reflect.Method;

/**
 * 
 * @author <a href="mailto:hedyn@foxmail.com">HeDYn</a>
 *
 */
class AnnotationEventFilter extends AnnotationPriority implements IEventFilter<Object> {
    
    private final String address;
    private final int priority;

    AnnotationEventFilter(Object invokedObject, Method method) {
        super(invokedObject, method);
        EventFilter annotation = method.getAnnotation(EventFilter.class);
        priority = annotation.priority();
        if (annotation.address() == null || annotation.address().isEmpty()) {
            Class<?> paramType = method.getParameterTypes()[0];
            address = paramType.getName();
        } else {
            address = annotation.address();
        }
    }

    @Override
    public void filter(Object event, EventFilterChain<Object> chain) {
        Class<?>[] parameterTypes = invokedMethod.getParameterTypes();
        if (parameterTypes.length != 2) {
            throw new RuntimeException("The method is invalid. method=" + invokedMethod);
        }
        try {
            invokedMethod.invoke(invokedObject, event, chain);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
    
    @Override
    protected String getAddress() {
        return address;
    }

    @Override
    public int getPriority() {
        return priority;
    }

}
